<script setup>
  import { ref, onMounted } from 'vue'

  const shopStore = useShopPinia()
  const selectedValue = ref([])
  const selectedCategories = ref([])

  // 处理分类变化
  const handleCategoryChange = (values) => {
    selectedCategories.value = values
      .map((id) => {
        return shopStore.商品一级分类.find((cat) => cat.ID === id)
      })
      .filter(Boolean)

    // shopStore.updateSelectedCategories(selectedCategories.value)

    // 触发父组件更新
    emit('update:modelValue', selectedCategories.value)
  }

  // 移除分类
  const removeCategory = (category) => {
    selectedValue.value = selectedValue.value.filter((id) => id !== category.ID)
    handleCategoryChange(selectedValue.value)
  }

  onMounted(async () => {
    await shopStore.获取商品分类api()
  })

  // 定义 props 和 emits
  const props = defineProps({
    modelValue: {
      type: Array,
      default: () => [],
    },
  })

  const emit = defineEmits(['update:modelValue'])
</script>

<template>
  <div class="category-select">
    <!-- 已选择的分类展示 -->
    <!-- <div v-if="selectedCategories.length" class="mb-4">
      <el-tag
        v-for="cat in selectedCategories"
        :key="cat.ID"
        class="mr-2"
        closable
        @close="removeCategory(cat)"
      >
        {{ cat.name }}
      </el-tag>
    </div> -->
    <!-- 分类选择器 -->
    <!-- multiple -->

    <el-select
      v-model="selectedValue"
      class="w-full"
      placeholder="请选择经营类目"
      filterable
      :multiple-limit="5"
      @change="handleCategoryChange"
    >
      <el-option
        v-for="item in shopStore.获取商家签约分类"
        :key="item.ID"
        :label="item.name"
        :value="item.ID"
      />
    </el-select>
  </div>
</template>

<style scoped>
  .category-select {
    width: 100%;
    padding: 16px;
    border-radius: 4px;
  }
  /* background: #fff; */

</style>
